package com.example.nutritionmate.controller;

import com.example.nutritionmate.dto.UpdateUserDTO;
import com.example.nutritionmate.dto.UserDTO;
import com.example.nutritionmate.entity.User;
import com.example.nutritionmate.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取当前认证用户的信息
     * 客户端需要在请求头中包含有效的 JWT Token，如：
     * Authorization: Bearer <token>
     */
    @GetMapping("/me")
    public ResponseEntity<?> getCurrentUser(@AuthenticationPrincipal UserDetails userDetails) {
        if (userDetails == null) {
            return ResponseEntity.status(403).body("未认证或Token无效");
        }

        Optional<User> optionalUser = userService.findByUsername(userDetails.getUsername());
        if (!optionalUser.isPresent()) {
            return ResponseEntity.status(404).body("用户不存在");
        }

        UserDTO userDTO = userService.convertToDTO(optionalUser.get());
        return ResponseEntity.ok(userDTO);
    }

    /**
     * 更新当前认证用户的信息
     * 客户端需要在请求头中包含有效的 JWT Token，如：
     * Authorization: Bearer <token>
     * 并在请求体中包含需要更新的字段
     */
    @PutMapping("/me")
    public ResponseEntity<?> updateCurrentUser(@AuthenticationPrincipal UserDetails userDetails,
                                               @RequestBody UpdateUserDTO updateUserDTO) {
        try {
            User updatedUser = userService.updateUser(userDetails.getUsername(), updateUserDTO);
            UserDTO userDTO = userService.convertToDTO(updatedUser);
            return ResponseEntity.ok(userDTO);
        } catch (RuntimeException e) {
            return ResponseEntity.status(400).body(e.getMessage());
        }
    }
}
